<template>
  <div>
    <!--下部tab-->
    <div
      id="goods-activity__form"
      v-loading="submitLoading"
      element-loading-text="提交中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <el-row :gutter="20">
        <el-form
          :model="form"
          :rules="formRules"
          ref="refForm"
          label-width="100px"
          size="small"
        >
          <el-col :span="12">
            <div class="left-form">
              <el-form-item label="活动名称" class="name" prop="name">
                <el-input
                  type="text"
                  v-model="form.name"
                  placeholder="请输入活动名称"
                  maxlength="40"
                  show-word-limit
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="活动时效">
                <el-radio-group
                  v-model="form.activityTimeData.activityTimeType"
                >
                  <el-radio
                    :label="item.value"
                    v-for="(item, index) of activityTimeTypeList"
                    :key="index"
                    >{{ item.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
              <!-- 长期有效下的活动时间 -->
              <div
                v-if="form.activityTimeData.activityTimeType == 'LONG_TERM'"
                class="form-item__longTeam"
              >
                <el-form-item label="活动时间">
                  <el-select
                    v-model="form.activityTimeData.activityStartTimeType"
                  >
                    <el-option
                      v-for="(item, index) of activityStartTimeTypeList"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                      >{{ item.label }}</el-option
                    >
                  </el-select>
                </el-form-item>
                <!-- 定时日期 -->
                <el-form-item
                  label-width="10px"
                  prop="activityTimeData.configTime.activityStartTime"
                  v-if="
                    form.activityTimeData.activityStartTimeType ===
                      'TIMED_START'
                  "
                >
                  <el-date-picker
                    v-model="form.activityTimeData.configTime.activityStartTime"
                    type="datetime"
                    placeholder="选择日期时间"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="timestamp"
                    @change="changeActivityStartTime"
                  >
                  </el-date-picker>
                </el-form-item>
              </div>
              <!-- 指定时间段下的活动时间 -->
              <el-form-item
                v-if="
                  form.activityTimeData.activityTimeType === 'SPECIFIED_TIME'
                "
                label="活动时间"
                prop="activityTimeData.configTimes"
              >
                <el-date-picker
                  v-model="form.activityTimeData.configTimes"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="timestamp"
                  @change="changeConfigTimes"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="活动类型" prop="activityType">
                <el-select
                  v-model="form.activityType"
                  placeholder="请选择活动类型"
                  @change="changeActivityType"
                >
                  <el-option
                    v-for="(item, index) of activityTypeList"
                    :key="index"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
              <!-- 参与条件 -->
              <div
                v-if="form.activityType === 'PRESENTING_COURSE'"
                class="form-item__partakeType"
              >
                <el-form-item
                  label="参与条件"
                  prop="conditionData.conditionOfParticipation.conditionType"
                >
                  <el-select
                    v-model="
                      form.conditionData.conditionOfParticipation.conditionType
                    "
                    @change="changeConditionType"
                  >
                    <el-option
                      :label="item.dictLabel"
                      :value="item.dictValue"
                      v-for="(item, index) of partakeConditionList"
                      :key="index"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <!-- 试听 -->
                <div
                  v-if="
                    form.conditionData.conditionOfParticipation
                      .conditionType === 'AUDITION'
                  "
                  class="partakeType-item"
                >
                  <el-form-item
                    label="至少"
                    label-width="50px"
                    prop="conditionData.conditionOfParticipation.conditionOfAuditionData.configDuration"
                  >
                    <el-input-number
                      v-model="
                        form.conditionData.conditionOfParticipation
                          .conditionOfAuditionData.configDuration
                      "
                      placeholder="试听时长"
                      :controls="false"
                      :precision="0"
                      :min="1"
                      :max="100"
                    ></el-input-number>
                  </el-form-item>
                  <el-select
                    v-model="
                      form.conditionData.conditionOfParticipation
                        .conditionOfAuditionData.unit
                    "
                    class="timeType-select"
                    size="small"
                  >
                    <el-option
                      :label="item.dictLabel"
                      :value="item.dictValue"
                      v-for="(item, index) of unitTypeList"
                      :key="index"
                    ></el-option>
                  </el-select>
                </div>
                <!-- 看课 -->
                <div
                  v-else-if="
                    form.conditionData.conditionOfParticipation
                      .conditionType === 'WATCH'
                  "
                  class="partakeType-item"
                >
                  <el-form-item
                    label="至少"
                    label-width="50px"
                    prop="conditionData.conditionOfParticipation.conditionOfWatchData.configDuration"
                  >
                    <el-input-number
                      v-model="
                        form.conditionData.conditionOfParticipation
                          .conditionOfWatchData.configDuration
                      "
                      placeholder="听课时长"
                      :controls="false"
                      :precision="0"
                      :min="1"
                      :max="100"
                    ></el-input-number>
                  </el-form-item>
                  <el-select
                    v-model="
                      form.conditionData.conditionOfParticipation
                        .conditionOfWatchData.unit
                    "
                    class="timeType-select"
                    size="small"
                  >
                    <el-option
                      :label="item.dictLabel"
                      :value="item.dictValue"
                      v-for="(item, index) of unitTypeList"
                      :key="index"
                    ></el-option>
                  </el-select>
                </div>
                <!-- 提交作业 -->
                <div
                  v-else-if="
                    form.conditionData.conditionOfParticipation
                      .conditionType === 'SUBMITTING_ASSIGNMENTS'
                  "
                >
                  <el-form-item
                    label-width="10px"
                    prop="conditionData.conditionOfParticipation.conditionOfSubmitAssignmentData.assignmentCount"
                  >
                    <el-input-number
                      v-model="
                        form.conditionData.conditionOfParticipation
                          .conditionOfSubmitAssignmentData.assignmentCount
                      "
                      placeholder="提交作业份数"
                      :controls="false"
                      :precision="0"
                      :min="1"
                      :max="100"
                    ></el-input-number>
                    <span class="partakeType-item__tip">（份数）</span>
                  </el-form-item>
                </div>
              </div>
              <!-- 参与课程 -->
              <el-form-item label="参与课程" v-if="showCourseRange" prop="conditionData.conditionOfParticipation.courseRange">
                <el-select
                  v-model="
                    form.conditionData.conditionOfParticipation.courseRange
                  "
                  placeholder="请选择课程类型"
                  @change="changeCourseRange"
                >
                  <el-option
                    :label="item.label"
                    :value="item.value"
                    v-for="(item, index) of courseRangeTypeList"
                    :key="index"
                  ></el-option>
                </el-select>
                <el-button
                  v-if="showCourseList"
                  icon="el-icon-plus"
                  class="form-item__action"
                  type="success"
                  @click="handleChoose('COURSE')"
                  >选择课程</el-button
                >
              </el-form-item>
              <!-- 课程列表 -->
              <courseTable
                v-if="showCourseList && showCourseRange"
                :courseData="courseDialogData.courseList"
                @deleteCourse="deleteCourse"
              />
              <el-form-item label="赠送商品" prop="giftedCourses">
                <el-button
                  icon="el-icon-plus"
                  class="form-item__action"
                  type="success"
                  @click="handleChoose('GOODS')"
                  >选择商品</el-button
                >
              </el-form-item>
              <!-- 商品列表 -->
              <goodsTable
                :goodsData="goodsDialogData.goodsList"
                @deleteGoods="deleteGoods"
              />
              <!-- 参与课程 -->
              <el-form-item
                v-if="
                  form.conditionData.conditionOfParticipation.conditionType !==
                    'GIFT'
                "
                label="参与用户"
                prop="courseList"
              >
                <el-select
                  v-model="form.activityUserRangeConfig.userRangeType"
                  placeholder="请选择参与用户"
                >
                  <el-option
                    :label="item.dictLabel"
                    :value="item.dictValue"
                    :disabled="item.disabled"
                    v-for="(item, index) of userParticipateList"
                    :key="index"
                  ></el-option>
                </el-select>
                <el-button
                  v-if="
                    form.activityUserRangeConfig.userRangeType === 'SPECIFY'
                  "
                  icon="el-icon-plus"
                  class="form-item__action"
                  type="success"
                  @click="handleChoose('USERTYPE')"
                  >选择用户分组</el-button
                >
              </el-form-item>

              <!-- 参与课程 -->
              <el-form-item v-else label="发放用户" prop="courseList">
                <el-select
                  v-model="form.activityUserRangeConfig.userRangeType"
                  placeholder="请选择发放用户"
                >
                  <el-option
                    :label="item.dictLabel"
                    :value="item.dictValue"
                    :disabled="item.disabled"
                    v-for="(item, index) of userRangeTypeList"
                    :key="index"
                  ></el-option>
                </el-select>
                <el-button
                  v-if="
                    form.activityUserRangeConfig.userRangeType === 'SPECIFY'
                  "
                  icon="el-icon-plus"
                  class="form-item__action"
                  type="success"
                  @click="handleChoose('USERTYPE')"
                  >选择用户分组</el-button
                >
              </el-form-item>
              <!-- 课程列表 -->
              <groupTable
                v-if="form.activityUserRangeConfig.userRangeType === 'SPECIFY'"
                :courseList="courseList"
                @deleteGrouping="deleteGrouping"
              />
            </div>
          </el-col>
          <el-col :span="12">
            <div class="right-form">
              <el-form-item
                label="活动凭证(图)"
                prop="activityVoucher.activityVoucherImages"
              >
                <uploadImg
                  ref="clsImg"
                  :img-array="form.activityVoucher.activityVoucherImages"
                  :accept="'.jpg,.png'"
                  :max-size="5"
                  :preview-img="false"
                  :single-file="45"
                  @setImgInfo="setImgInfo"
                ></uploadImg>
              </el-form-item>
              <el-form-item
                label="活动凭证(文)"
                prop="activityVoucher.activityVoucherDescription"
              >
                <el-input
                  type="textarea"
                  :rows="5"
                  show-word-limit
                  maxlength="2000"
                  placeholder="请输入不超过2000字内容"
                  v-model="form.activityVoucher.activityVoucherDescription"
                >
                </el-input>
              </el-form-item>
            </div>
          </el-col>
        </el-form>
      </el-row>
      <div class="bottom-btn">
        <el-button size="medium" type="success" @click="submitForm('refForm')"
          >提交</el-button
        >
      </div>
    </div>
    <!-- 选择课程弹窗 -->
    <chooseCourseDialog
      v-if="courseDialogData.isShow"
      :courseType="courseType"
      :dialog-data="courseDialogData"
      @setCourseList="setCourseList"
    />
    <!-- 选择课程弹窗 -->
    <userGroupingDialog
      v-if="userGroupingData"
      :userGroupingDataShow.sync="userGroupingData"
      :courseList="courseList"
      @setUserGroupingList="setUserGroupingList"
    />
    <!-- 选择商品弹窗 -->
    <chooseGoodsDialog
      v-if="goodsDialogData.isShow"
      :dialog-data="goodsDialogData"
      @setGoodsList="setGoodsList"
    />
    <!-- <importDialog
      v-if="importDialogData.isShow"
      :dialog-data="importDialogData"
      @showError="showError"
      @getSerial="getSerial"
    /> -->
    <!-- <errorDialog
      v-if="errorDialogData.isShow"
      :dialog-data="errorDialogData"
      :from="downFailInfo"
    /> -->
  </div>
</template>

<script>
import { sysNormalDisable } from '@utils/dictionariesFunc'
import { clearTagMixins } from '@/mixins/clearTag'

import {
  validatorActivityName,
  downTemplate,
  addGivingCourses,
  getGivingCoursesDetail,
  editGivingCourses
} from '@/api/goodsActivityManagement'
import uploadImg from '@common/uploadImg' // 上传图片公共组件
import chooseCourseDialog from '@component/goodsActivityManagement/components/chooseCourseDialog'
import chooseGoodsDialog from '@component/goodsActivityManagement/components/chooseGoodsDialog'
import userGroupingDialog from '@component/goodsActivityManagement/components/userGroupingDialog'
import courseTable from '@component/goodsActivityManagement/components/courseTable'
import goodsTable from '@component/goodsActivityManagement/components/goodsTable'
import groupTable from '@component/goodsActivityManagement/components/groupTable'
// import importDialog from '@common/importDialog' // 导入分发用户弹窗
// import errorDialog from '@common/errorDialog' // 导入失败弹窗

const defaultAuditionData = {
  courseRange: null, //赠课活动试听条件课程范围
  configDuration: 1, //赠课活动试听条件试听时长
  specifyCourseIds: [], //赠课活动试听条件指定课程Ids
  unit: 'MINUTES'
}
const defaultSubmitAssignmentData = {
  assignmentCount: 1, //提交作业数
  courseRange: null, //课程范围
  specifyCourseIds: [] //课程Ids
}
const defaultWatchData = {
  courseRange: null, //看课条件课程范围
  configDuration: 1, //看课时长
  specifyCourseIds: [], //课程Ids
  unit: 'MINUTES' //看课时长单位
}
export default {
  mixins: [clearTagMixins],
  components: {
    uploadImg,
    courseTable,
    goodsTable,
    chooseCourseDialog,
    chooseGoodsDialog,
    userGroupingDialog,
    // importDialog, //导入分发用户弹窗
    // errorDialog,
    groupTable
  },
  data() {
    const _this = this
    return {
      // 传给选择商品弹窗 判断如果为试听的话 把参数VIP改为TRIAL
      courseType: '',
      downFailInfo: 'downUserIssue',
      // 导入失败弹框的数据
      // errorDialogData: {
      //   isShow: false, // 控制弹框显示
      //   warningText: '' // 参数
      // },
      //  导入分发用户弹窗
      // importDialogData: {
      //   title: '',
      //   isShow: false // 控制弹框显示
      // },
      userGroupingData: false, // 分组列表展示与隐藏
      courseList: [], // 分组列表
      goodsList: {}, // 点开分组列表回显
      // 课程弹窗数据
      courseDialogData: {
        isShow: false,
        courseList: []
      },
      // 商品弹窗数据
      goodsDialogData: {
        isShow: false,
        goodsList: []
      },
      // 提交加载状态
      submitLoading: false,
      // 配置活动时间
      configTimes: [],
      // 编辑时的原活动名称
      oldActivityName: '',
      form: {
        activityTimeData: {
          activityStartTimeType: 'IMMEDIATE_START', //赠课活动开始时间类型
          activityTimeType: 'LONG_TERM', //赠课活动时效类型
          configTimes: [],
          //赠课活动配置时间
          configTime: {
            activityEndTime: null,
            activityStartTime: null
          }
        },
        activityType: '', //赠课活动类型
        //赠课活动发放用户配置
        activityUserRangeConfig: {
          userRangeType: '',
          groupId: []
        },
        //赠课活动凭证配置
        activityVoucher: {
          activityVoucherDescription: '',
          activityVoucherImages: []
        },
        //赠课活动条件配置数据
        conditionData: {
          //赠课活动试听条件配置数据
          conditionOfParticipation: {
            conditionOfAuditionData: {
              courseRange: '', //赠课活动试听条件课程范围
              configDuration: 1, //赠课活动试听条件试听时长
              specifyCourseIds: [], //赠课活动试听条件指定课程Ids
              unit: 'MINUTES'
            },
            //赠课活动看课条件配置数据
            conditionOfWatchData: {
              courseRange: '', //看课条件课程范围
              configDuration: 1, //看课时长
              specifyCourseIds: [], //课程Ids
              unit: 'MINUTES' //看课时长单位
            },
            //赠课活动提交作业条件配置数据
            conditionOfSubmitAssignmentData: {
              assignmentCount: 1, //提交作业数
              courseRange: '', //课程范围
              specifyCourseIds: [] //课程Ids
            },
            conditionType: '', //条件类型
            courseRange: 'ALL'
          }
        },
        //活动赠课
        giftedCourses: [],
        name: '' //赠课活动名称
        // serial: '' //导入用户成功后获取的序列号
      },
      formRules: {
        name: [
          {
            required: true,
            message: '活动名称不能为空',
            trigger: 'blur'
          },
          {
            max: 40,
            message: '请输入不超过40个字符的内容',
            trigger: 'blur'
          },
          {
            validator: _this.checkActivityName,
            trigger: 'blur'
          }
        ],
        activityType: {
          required: true,
          message: '请选择活动类型',
          trigger: 'change'
        },
        'activityTimeData.configTime.activityStartTime': [
          {
            required: true,
            message: '请选择日期时间',
            trigger: 'change'
          }
        ],
        'activityTimeData.configTimes': [
          {
            required: true,
            message: '请选择指定时间段活动时间',
            trigger: 'change'
          }
        ],
        'conditionData.conditionOfParticipation.conditionType': [
          {
            required: true,
            message: '请选择参与条件',
            trigger: 'change'
          }
        ],
        'conditionData.conditionOfParticipation.courseRange' :[
          {
            required: true,
            message: '请选择参与课程',
            trigger: 'change'
          }
        ],
        'activityUserRangeConfig.userRangeType': [
          { required: true, message: '请选择发放用户类型', trigger: 'change' },
          { validator: _this.checkUserRangeType, trigger: 'change' }
        ],
        'activityVoucher.activityVoucherImages': {
          validator: _this.checkActivityVoucherImages,
          trigger: 'change'
        },
        'activityVoucher.activityVoucherDescription': {
          validator: _this.checkActivityVoucherDescription,
          trigger: 'blur'
        },
        giftedCourses: {
          validator: _this.checkGiftedCourses,
          trigger: 'blur'
        },
        courseList: {
          validator: _this.checkGrouping,
          trigger: 'blur'
        }
      },
      activityTimeTypeList: [
        { label: '长期有效', value: 'LONG_TERM' },
        { label: '指定时间段', value: 'SPECIFIED_TIME' }
      ],
      activityStartTimeTypeList: [
        { label: '立即开始', value: 'IMMEDIATE_START' },
        { label: '定时开始', value: 'TIMED_START' }
      ],

      // 课程类型参与条件
      courseTypeList: [
        { label: '全部课程', value: 'ALL' },
        { label: '指定课程', value: 'SPECIFY' }
      ],
      // 试听的参与课程
      auditionTypeList: [
        { label: '全部试听课程', value: 'ALL' },
        { label: '指定试听课程', value: 'SPECIFY' }
      ],
      // 活动类型
      activityTypeList: [{ dictLabel: '请选择活动类型', dictValue: '' }],
      // 参与条件
      partakeConditionList: [],
      // 时间单位
      unitTypeList: [],
      // 发放用户
      userRangeTypeList: [{ dictLabel: '选择发放用户', dictValue: '' }],
      userParticipateList: [{ dictLabel: '选择参与用户', dictValue: '' }],
      groupId: []
    }
  },
  computed: {
    showCourseRange() {
      if (
        this.form.conditionData.conditionOfParticipation.conditionType === '' ||
        this.form.conditionData.conditionOfParticipation.conditionType ===
          'GIFT'
      ) {
        return false
      } else {
        return true
      }
    },
    // 显示选择课程、课程列表
    showCourseList() {
      if (
        this.form.conditionData.conditionOfParticipation.courseRange === 'ALL'
      ) {
        return false
      } else {
        return true
      }
    },
    courseRangeTypeList() {
      let rangeTypeList = null
      switch (this.form.conditionData.conditionOfParticipation.conditionType) {
        case 'AUDITION':
          rangeTypeList = this.auditionTypeList
          break
        case 'WATCH':
        case 'SUBMITTING_ASSIGNMENTS':
          rangeTypeList = this.courseTypeList
          break
        default:
          break
      }
      return rangeTypeList
    }
  },
  created() {},
  async mounted() {
    let [
      activityTypeData,
      userRangeTypeData,
      conditionTypeData,
      timeTypeData
    ] = await Promise.all([
      sysNormalDisable('activity_course_type', 'activity_course_type'),
      sysNormalDisable(
        'activity_course_user_type',
        'activity_course_user_type'
      ),
      sysNormalDisable('giving_condition_type', 'giving_condition_type'),
      sysNormalDisable('giving_course_time_type', 'giving_course_time_type'),
      sysNormalDisable('goods_type', 'goods_type')
    ])
    this.activityTypeList = [...this.activityTypeList, ...activityTypeData]
    this.userRangeTypeList = [...this.userRangeTypeList, ...userRangeTypeData]
    this.userParticipateList = [
      ...this.userParticipateList,
      ...userRangeTypeData
    ]

    this.partakeConditionList = conditionTypeData
    console.log(this.partakeConditionList)
    this.unitTypeList = timeTypeData
    if (this.$route.query.id) {
      getGivingCoursesDetail(
        this.$route.query.id,
        {},
        (res) => {
          // 课程类型下拉赋值
          res.conditionData.conditionOfParticipation.courseRange = this.convertUserRange(
            res.conditionData
          )
          // // 活动配置时间赋值
          res.activityTimeData.configTimes = this.convertConfigTimes(
            res.activityTimeData.configTime
          )
          this.oldActivityName = res.name
          this.form = res

          console.log(res)
          this.courseDialogData.courseList = res.givingCourseInfosResourceList
          this.goodsDialogData.goodsList = res.coursesGoodsDtoList
          this.courseList = res.activityUserRangeConfig.groupId
          this.form.activityUserRangeConfig.groupId = res.activityUserRangeConfig.groupId.map(
            (item) => {
              return item.id
            }
          )
          console.log(this.goodsDialogData.goodsList)
        },
        (err) => {}
      )
    } else if (localStorage.getItem('goodsActivityInfo')) {
      const goodsActivityInfo = JSON.parse(
        localStorage.getItem('goodsActivityInfo')
      )
      this.form = goodsActivityInfo.form
      this.goodsDialogData.goodsList = this.form.giftedCourses
      this.courseDialogData.courseList = goodsActivityInfo.courseList
    }
    this.form.conditionData.conditionOfParticipation.conditionType = 'AUDITION'
    if (
      (this.form.conditionData.conditionOfParticipation.conditionType =
        'AUDITION')
    ) {
      this.form.conditionData.conditionOfParticipation.conditionOfSubmitAssignmentData = {
        ...defaultSubmitAssignmentData
      }
      this.form.conditionData.conditionOfParticipation.conditionOfWatchData = {
        ...defaultWatchData
      }
    }
  },
  watch: {
    'form.activityUserRangeConfig.groupId': {
      handler(newV, oldV) {
        console.log(newV, oldV)
      },
      deep: 'true'
    },
    'goodsDialogData.goodsList': {
      handler(newV, oldV) {
        this.form.giftedCourses = newV
        if (newV.length > 0) {
          this.$refs['refForm'].clearValidate('giftedCourses')
        }
      },
      deep: 'true'
    },
    'form.conditionData.conditionOfParticipation.conditionType': {
      handler(newV, oldV) {
        let userRangeTypeList = this.userRangeTypeList
        let userParticipateList = this.userParticipateList
        const userRangeType = this.form.activityUserRangeConfig.userRangeType
        // 如果参与条件是赠送类型禁止全局用户发放
        if (newV === 'GIFT' && userRangeType === 'GLOBAL') {
          this.form.activityUserRangeConfig.userRangeType = ''
        }
        this.userRangeTypeList = userRangeTypeList.map((item) => {
          if (newV === 'GIFT' && item.dictValue === 'GLOBAL') {
            item.disabled = true
          } else {
            item.disabled = false
          }
          return item
        })
        this.userParticipateList = userParticipateList.map((item) => {
          if (newV === 'GIFT' && item.dictValue === 'GLOBAL') {
            item.disabled = true
          } else {
            item.disabled = false
          }
          return item
        })
      },
      deep: 'true'
    }
  },
  methods: {
    signOut() {
      this.$router.go(-1)
    },
    getSerial(val) {
      if (val) {
        this.form.serial = val
      }
    },
    // /* 导入失败弹窗 */
    // showError(text) {
    //   this.errorDialogData.isShow = true
    //   this.errorDialogData.warningText = text // 显示导入失败弹框
    // },
    // 分发用户的定向用户的导入文件
    // importFile() {
    //   this.importDialogData.url = '/giving-courses/users/binding' // 导入接口
    //   this.importDialogData.downUrl = downTemplate() // 下载模板接口
    //   this.importDialogData.isShow = true // 显示导入弹框
    //   this.importDialogData.title = '用户导入'
    // },
    // 校验活动名称是否存在
    checkActivityName(rule, value, callback) {
      if (this.oldActivityName && value === this.oldActivityName) {
        callback()
      } else {
        validatorActivityName(
          {
            type: 'name',
            name: value
          },
          (response) => {
            if (response) {
              callback(new Error('活动名称已存在'))
            } else {
              callback()
            }
          }
        )
      }
    },
    // 校验是否存在上传图片或者描述
    checkActivityVoucherImages(rule, value, callback) {
      if (
        value.length === 0 &&
        !this.form.activityVoucher.activityVoucherDescription
      ) {
        callback(new Error('请上传活动凭证'))
      } else {
        this.$refs['refForm'].clearValidate(
          'activityVoucher.activityVoucherDescription'
        )
        callback()
      }
    },
    // 校验是否存在上传图片或者描述
    checkActivityVoucherDescription(rule, value, callback) {
      if (
        this.form.activityVoucher.activityVoucherImages.length === 0 &&
        !value
      ) {
        callback(new Error('请输入活动凭证'))
      } else {
        this.$refs['refForm'].clearValidate(
          'activityVoucher.activityVoucherImages'
        )
        callback()
      }
    },
    // 校验发放用户如果是定向用户是否选择分组
    checkUserRangeType(rule, value, callback) {
      if (this.$route.query.id && value === 'SPECIFY') {
        callback()
      } else if (!this.form.serial && value === 'SPECIFY') {
        callback(new Error('请选择用户分组'))
      } else {
        callback()
      }
    },
    // 校验赠送商品
    checkGiftedCourses(rule, value, callback) {
      if (value.length === 0) {
        callback(new Error('请选择赠送商品'))
      } else {
        callback()
      }
    },
    checkGrouping(rule, value, callback) {
      // if (this.form.activityUserRangeConfig.userRangeType === 'SPECIFY') {
      //   callback()
      // } else if (!this.form.activityUserRangeConfig.userRangeType === 'SPECIFY') {
        
      //   callback(new Error('请选择用户分组'))
      // } else {
      //   callback()
      // }
      if (this.form.activityUserRangeConfig.userRangeType === 'GLOBAL') {
        callback()
      } else {
        if (this.courseList.length === 0) {
          callback(new Error('请选择用户分组'))
        } else {
          callback()
        }
      }
    },
    // 参与条件改变
    changeConditionType(val) {
      // 设置类型改为默认值
      console.log(this.partakeConditionList)
      console.log(val)
      console.log(
        this.form.conditionData.conditionOfParticipation.conditionType
      )
      const res = this.partakeConditionList.filter((item) => {
        return item.dictValue == val
      })
      console.log(res)
      if (res[0].dictValue == val) {
        this.courseDialogData.courseList = []
        this.goodsDialogData.goodsList = []
        this.form.conditionData.conditionOfParticipation.courseRange = ''
        this.form.activityVoucher.activityVoucherDescription = ''
        // 清除图片
        this.$refs.clsImg.clearList()
        this.form.activityUserRangeConfig.userRangeType = ''
        // this.form.conditionData.conditionOfWatchData.conditionOfParticipation.courseRange = ''
        // this.form.conditionData.conditionOfSubmitAssignmentData.courseRange = ''
      }
      switch (val) {
        case 'AUDITION':
          this.form.conditionData.conditionOfParticipation.conditionOfSubmitAssignmentData = {
            ...defaultSubmitAssignmentData
          }
          this.form.conditionData.conditionOfParticipation.conditionOfWatchData = {
            ...defaultWatchData
          }
          break
        case 'WATCH':
          this.form.conditionData.conditionOfParticipation.conditionOfAuditionData = {
            ...defaultAuditionData
          }
          this.form.conditionData.conditionOfParticipation.conditionOfSubmitAssignmentData = {
            ...defaultSubmitAssignmentData
          }
          break
        case 'SUBMITTING_ASSIGNMENTS':
          this.form.conditionData.conditionOfParticipation.conditionOfAuditionData = {
            ...defaultAuditionData
          }
          this.form.conditionData.conditionOfParticipation.conditionOfWatchData = {
            ...defaultWatchData
          }
          break
        case 'GIFT':
          this.form.conditionData.conditionOfParticipation.conditionOfAuditionData = {
            ...defaultAuditionData
          }
          this.form.conditionData.conditionOfParticipation.conditionOfSubmitAssignmentData = {
            ...defaultSubmitAssignmentData
          }
          this.form.conditionData.conditionOfParticipation.conditionOfWatchData = {
            ...defaultWatchData
          }
          break
        default:
          break
      }
      this.clearCourseList()
      this.clearGroupingList()
    },
    // 指定时间段下活动时间切换
    changeConfigTimes(val) {
      if (val) {
        this.form.activityTimeData.configTime.activityStartTime = val[0]
        this.form.activityTimeData.configTime.activityEndTime = val[1]
      } else {
        this.form.activityTimeData.configTime.activityStartTime = null
        this.form.activityTimeData.configTime.activityEndTime = null
      }
    },
    // 切换选择课程类型
    changeCourseRange(val) {
      switch (this.form.conditionData.conditionOfParticipation.conditionType) {
        case 'AUDITION':
          this.form.conditionData.conditionOfParticipation.conditionOfAuditionData.courseRange = val
          break
        case 'WATCH':
          this.form.conditionData.conditionOfParticipation.conditionOfSubmitAssignmentData.courseRange = val
          break
        case 'SUBMITTING_ASSIGNMENTS':
          this.form.conditionData.conditionOfParticipation.conditionOfWatchData.courseRange = val
          break
        default:
          break
      }
      this.clearCourseList()
      this.clearGroupingList()
    },
    // 长期有效下将结束时间置为null
    changeActivityStartTime() {
      this.form.activityTimeData.configTime.activityEndTime = null
    },
    // 设置添加按钮事件（课程、商品）
    handleChoose(type) {
      console.log(type)
      switch (type) {
        case 'COURSE':
          // 传参当为试听的时候 调用另一个参数接口
          this.courseType = this.form.conditionData.conditionOfParticipation.conditionType
          this.courseDialogData.isShow = true
          break
        case 'GOODS':
          this.goodsDialogData.isShow = true
          break
        case 'USERTYPE':
          this.userGroupingData = true
          break
        default:
          break
      }
    },
    // 获取活动类型
    changeActivityType(val) {
      if (!val) {
        this.form.conditionData.conditionOfParticipation.conditionType = ''
      }
    },
    // 设置课程选中的数据
    setCourseList(courseList) {
      this.courseDialogData.courseList = courseList
    },
    // 设置商品选中的数据
    setGoodsList(goodsList) {
      this.goodsDialogData.goodsList = goodsList
    },
    // 设置分组选中的数据
    setUserGroupingList(courseList) {
      console.log(courseList)
      let groupId = []
      courseList.forEach((item) => {
        groupId.push(item.id)
      })
      this.form.activityUserRangeConfig.groupId = groupId
      console.log(groupId)
      console.log(this.form.activityUserRangeConfig.groupId)
      this.courseList = courseList
      this.groupId = groupId
    },
    // 删除课程
    deleteCourse(index) {
      this.courseDialogData.courseList.splice(index, 1)
    },
    // 删除商品
    deleteGoods(index) {
      this.goodsDialogData.goodsList.splice(index, 1)
    },
    // 删除分组
    deleteGrouping(index) {
      this.courseList.splice(index, 1)
      this.groupId.splice(index, 1)
      this.form.activityUserRangeConfig.groupId.splice(index, 1)
      console.log(this.courseList)
      console.log(this.groupId)
    },
    // 上传图片返回数据
    setImgInfo(val) {
      if (val) {
        this.form.activityVoucher.activityVoucherImages = val.map((item) => {
          if (item.url) {
            return item.url
          } else {
            return item
          }
        })
      } else {
      }
    },
    // 清空选择课程
    clearCourseList() {
      this.courseDialogData.courseList = []
    },
    // 清空选择商品
    clearGoodsList() {
      this.goodsDialogData.goodsList = []
    },
    // 清空选择分组
    clearGroupingList() {
      this.courseList = []
    },
    // 转换参与条件类型
    convertUserRange(conditionData) {
      let courseRange = 'ALL'
      switch (conditionData.conditionOfParticipation.conditionType) {
        case 'AUDITION':
          courseRange =
            conditionData.conditionOfParticipation.conditionOfAuditionData
              .courseRange
          break
        case 'WATCH':
          courseRange =
            conditionData.conditionOfParticipation.conditionOfWatchData
              .courseRange
          break
        case 'SUBMITTING_ASSIGNMENTS':
          courseRange =
            conditionData.conditionOfParticipation
              .conditionOfSubmitAssignmentData.courseRange
          break
        default:
          break
      }
      return courseRange
    },
    // 时间转换
    convertConfigTimes(configTime) {
      let configTimeArray = []
      if (configTime.activityEndTime) {
        configTimeArray.push(configTime.activityStartTime)
        configTimeArray.push(configTime.activityEndTime)
      }
      return configTimeArray
    },
    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitLoading = true
          const courseRange = this.form.conditionData.conditionOfParticipation
            .courseRange
          let specifyCourseIds = []
          if (courseRange !== 'ALL') {
            specifyCourseIds = this.courseDialogData.courseList.map((item) => {
              return item.id
            })
          }
          switch (
            this.form.conditionData.conditionOfParticipation.conditionType
          ) {
            case 'AUDITION':
              this.form.conditionData.conditionOfParticipation.conditionOfAuditionData.specifyCourseIds = specifyCourseIds
              this.form.conditionData.conditionOfParticipation.conditionOfAuditionData.courseRange = courseRange
              break
            case 'WATCH':
              this.form.conditionData.conditionOfParticipation.conditionOfWatchData.specifyCourseIds = specifyCourseIds
              this.form.conditionData.conditionOfParticipation.conditionOfWatchData.courseRange = courseRange
              break
            case 'SUBMITTING_ASSIGNMENTS':
              this.form.conditionData.conditionOfParticipation.conditionOfSubmitAssignmentData.specifyCourseIds = specifyCourseIds
              this.form.conditionData.conditionOfParticipation.conditionOfSubmitAssignmentData.courseRange = courseRange
              break
            default:
              break
          }
          this.form.giftedCourses = this.goodsDialogData.goodsList

          if (this.$route.query.id) {
            // 当时间为定时时间
            const self = this
            if (
              self.form.activityTimeData.activityStartTimeType === 'TIMED_START'
            ) {
              if (
                self.form.activityTimeData.configTime.activityStartTime <
                Date.now()
              ) {
                self.submitLoading = false
                self.$message({
                  message: '定时时间不能小于当前时间',
                  type: 'warning'
                })
                return false
              }
            }
            // 如果是定时时间的话
            if (
              self.form.activityTimeData.activityTimeType === 'SPECIFIED_TIME'
            ) {
              if (self.form.activityTimeData.configTimes[0] < Date.now()) {
                self.submitLoading = false
                self.$message({
                  message: '开始时间不能小于当前时间',
                  type: 'warning'
                })
                return false
              }
            }

            editGivingCourses(
              this.form,
              (res) => {
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                this.submitLoading = false
                this.clearTag()
              },
              (err) => {
                this.$message({
                  message: err.message,
                  type: 'warning'
                })
                this.submitLoading = false
              }
            )
          } else {
            // 当时间为定时时间
            const self = this
            if (
              self.form.activityTimeData.activityStartTimeType === 'TIMED_START'
            ) {
              if (
                self.form.activityTimeData.configTime.activityStartTime <
                Date.now()
              ) {
                self.submitLoading = false
                self.$message({
                  message: '定时时间不能小于当前时间',
                  type: 'warning'
                })
                return false
              }
            }
            // 如果是定时时间的话
            if (
              self.form.activityTimeData.activityTimeType === 'SPECIFIED_TIME'
            ) {
              if (self.form.activityTimeData.configTimes[0] < Date.now()) {
                self.submitLoading = false
                self.$message({
                  message: '开始时间不能小于当前时间',
                  type: 'warning'
                })
                return false
              }
            }
            addGivingCourses(
              this.form,
              () => {
                this.$emit('changeSaveStatus')
                this.submitLoading = false
                this.clearTag()
              },
              (err) => {
                this.$message({
                  message: err.message,
                  type: 'warning'
                })
                this.submitLoading = false
              }
            )
          }
        }
      })
      this.$store.commit(
        'setUserType',
        this.form.conditionData.conditionOfParticipation.conditionType
      )
    }
  }
}
</script>

<style lang="less" scoped>
#goods-activity__form {
  :deep(.el-range-separator,
  .el-range__icon,
  .el-range__close-icon) {
    box-sizing: content-box;
    line-height: 22px;
  }
  :deep(.el-range-editor--small.el-input__inner) {
    height: 28px;
  }
  .left-form {
    .form-item__longTeam {
      display: flex;
    }
    .form-item__partakeType {
      display: flex;
      .partakeType-item {
        display: flex;
      }
    }
    .form-item__action {
      margin-left: 10px;
    }
    .timeType-select {
      width: 80px;
      margin-left: 10px;
    }
    .partakeType-item__tip {
      margin-left: 10px;
    }
  }
  .right-form {
    width: 580px;
    :deep(.el-upload-list--picture-card .el-upload-list__item) {
      margin: 0 8px 8px 0 !important;
    }
  }
  // 导入按钮样式
  // .import-btn {
  //   height: 32px;
  //   margin-left: 20px;
  // }
  // 提交按钮样式
  .bottom-btn {
    width: 100%;
    margin: 10px 0;
    text-align: center;
    .el-button {
      padding: 5px 30px;
    }
  }
}
</style>
